﻿using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Transport.Core.Models.Parcels;
using Transport.Services.Settings;

namespace Transport.Services.Parcels
{
    public class ParcelDeliveryService : IParcelDeliveryService
    {
        private readonly IParcelDeliveryGroupRepository _parcelDeliveryGroupRepository;
        private readonly IMyOfficeRepository _myOfficeRepository;
        private readonly IParcelPackagingItemRepository _parcelPackagingItemRepository;
        private readonly IStateProvinceRepository _stateProvinceRepository;
        private readonly IParcelPackagingGroupRepository _parcelPackagingGroupRepository;

        public ParcelDeliveryService(IParcelDeliveryGroupRepository parcelDeliveryGroupRepository, IMyOfficeRepository myOfficeRepository,
                                     IParcelPackagingItemRepository parcelPackagingItemRepository,
                                     IStateProvinceRepository stateProvinceRepository, IParcelPackagingGroupRepository parcelPackagingGroupRepository)
        {
            _parcelDeliveryGroupRepository = parcelDeliveryGroupRepository;
            _myOfficeRepository = myOfficeRepository;
            _parcelPackagingItemRepository = parcelPackagingItemRepository;
            _stateProvinceRepository = stateProvinceRepository;
            _parcelPackagingGroupRepository = parcelPackagingGroupRepository;
        }

        public MemoryStream DownloadParcelDelivery(int deliveryGroupId, int myOfficeId)
        {
            var parvelDeliveryGroup = _parcelDeliveryGroupRepository.GetAll()
                                    .Where(p => p.ParcelDeliveryGroupId == deliveryGroupId)
                                    .Include(p => p.User)
                                    .Include(p => p.ParcelDeliverys.Select(o => o.Parcel.Customer))
                                    .FirstOrDefault();
            if(parvelDeliveryGroup==null)
                return null;

            var pdfData = new MemoryStream();
            var document = new Document(PageSize.A4, 35, 35, 25, 50);
            var pdfWriter = PdfWriter.GetInstance(document, pdfData);
            pdfWriter.ViewerPreferences = PdfWriter.PageLayoutOneColumn;

            // Our custom Header and Footer is done using Event Handler
            var pageEventHandler = new TwoColumnHeaderFooter();
            pdfWriter.PageEvent = pageEventHandler;

            // Define the page header
            //pageEventHandler.Title = title;
            //pageEventHandler.HeaderFont = FontFactory.GetFont(BaseFont.COURIER_BOLD, 10, Font.BOLD);
            //pageEventHandler.HeaderLeft = "Group";
            //pageEventHandler.HeaderRight = "1";
            var filePath = System.IO.Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Content\\Fonts", "times.ttf");
            BaseFont baseFont = BaseFont.CreateFont("C:\\Windows\\Fonts\\times.ttf", BaseFont.IDENTITY_H, true);
            var fontBold = new Font(baseFont, 11, Font.BOLD, BaseColor.BLACK);
            Font defaultFont = new Font(baseFont, 11, Font.NORMAL, BaseColor.BLACK);

            document.Open();

            //Add header
            var tableColumnHearder = new PdfPTable(2) { WidthPercentage = 100 };
            var colWidthPercentagesHearder = new Single[] { 50, 50 };
            tableColumnHearder.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            tableColumnHearder.SetWidths(colWidthPercentagesHearder);

            string imagepath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Content\\images", "Logo TrungThanh Express.jpg");
            Image img = Image.GetInstance(imagepath);
            img.ScaleToFit(200f, 100f);
            img.Alignment = Image.ALIGN_LEFT;
            img.IndentationLeft = 0f;
            img.SpacingAfter = 9f;
            img.BorderWidthTop = 5f;
            img.BorderColorTop = BaseColor.WHITE;
            tableColumnHearder.AddCell(new PdfPCell(img) { BorderWidth = 0, Padding = 3, HorizontalAlignment = Element.ALIGN_LEFT });

            var office = _myOfficeRepository.GetById(myOfficeId);
            var myCompany = new Paragraph(office.OfficeName + Environment.NewLine + "Đ/C: " + office.Address + Environment.NewLine + "SĐT: " + office.PhoneNumber + (string.IsNullOrEmpty(office.Fax) ? string.Empty : " FAX: " + office.Fax), defaultFont);
            myCompany.Alignment = Element.ALIGN_RIGHT;
            tableColumnHearder.AddCell(new PdfPCell(myCompany) { BorderWidth = 0, Padding = 3, HorizontalAlignment = Element.ALIGN_RIGHT });
            document.Add(tableColumnHearder);

            //End header

            //document.Add(new Phrase("\n"));
            //var myCompanyAddress = new Chunk("Đ/C: SỐ 17 NGÁCH 43 NGÕ 64 NG.LƯƠNG BẰNG - ĐỐNG ĐA - HN", defaultFont);
            //document.Add(myCompanyAddress);
            //document.Add(new Phrase("\n"));
            //var myCompanyContact = new Chunk("SĐT: 04.3514.9969          FAX: 04.3573.9119", defaultFont);
            //document.Add(myCompanyContact);
            document.Add(new Paragraph("\r\n"));
            var myTitle = new Paragraph("BƯU PHẨM ĐI PHÁT", new Font(baseFont, 22, Font.BOLD, BaseColor.BLACK));
            myTitle.Alignment = Element.ALIGN_CENTER;
            document.Add(myTitle);
            document.Add(new Paragraph("\r\n"));

            //Employee Name
            var employeeName = new Chunk(" TÊN NHÂN VIÊN: " + parvelDeliveryGroup.User.FirstName + " " + parvelDeliveryGroup.User.LastName, defaultFont);
            document.Add(employeeName);
            document.Add(new Paragraph(""));
            //Report date
            var dateReport = new Chunk(" NGÀY: " + parvelDeliveryGroup.CreateDate.ToString("dd-MM-yyyy HH:mm:ss"), defaultFont);
            document.Add(dateReport);
            document.Add(new Paragraph("\r\n"));

            //Add columns
            var tableColumn = new PdfPTable(7) { WidthPercentage = 100 };
            var colWidthPercentages = new Single[] { 7, 13, 29, 12, 12, 15, 12};
            tableColumn.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            tableColumn.SetWidths(colWidthPercentages);
            tableColumn.AddCell(new PdfPCell(new Phrase("STT", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("S.VẬN ĐƠN", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("ĐỊA CHỈ", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("T.LƯỢNG", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("GIÁ TIỀN", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("NGƯỜI NHẬN", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("GHI CHÚ", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            document.Add(tableColumn);

            //Add rows
            var no = 1;
            foreach (var item in parvelDeliveryGroup.ParcelDeliverys)
            {
                var tableRow = new PdfPTable(7) { WidthPercentage = 100 };
                tableRow.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                tableRow.SetWidths(colWidthPercentages);
                tableRow.AddCell(new PdfPCell(new Phrase(no.ToString(), defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                tableRow.AddCell(new PdfPCell(new Phrase(item.Parcel.TrackingNumbers.ToUpper(), defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                tableRow.AddCell(new PdfPCell(new Phrase(item.Parcel.ToAddress, defaultFont)));
                tableRow.AddCell(new PdfPCell(new Phrase(item.Parcel.TotalWeight + "g", defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                if (item.Parcel.PaymentType == (int)PaymentTypes.EnumPaymentTypes.Collection)
                {
                    tableRow.AddCell(new PdfPCell(new Phrase(String.Format("{0:0,0}", item.Parcel.TotalCost), defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                }
                else
                {
                    tableRow.AddCell(new PdfPCell(new Phrase("N/A", defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                }
                tableRow.AddCell(new PdfPCell(new Phrase(item.Parcel.Receiver, defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                var success = item.Parcel.Status == (int)TrackingStatus.EnumTrackingStatus.Success ? " - " + TrackingStatus.GetStatus(item.Parcel.Status) : string.Empty;
                tableRow.AddCell(new PdfPCell(new Phrase(item.Parcel.Note + success, defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                document.Add(tableRow);
                no++;
            }

            document.Close();

            return pdfData;
        }


        public MemoryStream DownloadParcelPackaging(int packagingGroupId, int myOfficeId)
        {
            var query = from x in _parcelPackagingItemRepository.GetAll().Include(p => p.ParcelPackagingGroup.Region).Include(o => o.Parcel)
                        join s in _stateProvinceRepository.GetAll() on x.Parcel.DeliverToId equals s.StateProvinceId
                        where x.ParcelPackagingGroupId == packagingGroupId
                        orderby x.ParcelPackagingItemId descending
                        select new ParceldeliveryReportModel
                        {
                            AddressTo = x.Parcel.ToAddress,
                            CustomerId = x.Parcel.CustomerId,
                            CustomerName = x.Parcel.Customer.CustomerShortName,
                            DeliverToName = s.StateProvinceName,
                            Note = x.Parcel.Note,
                            TrackingNumbers = x.Parcel.TrackingNumbers,
                            Weight = x.Parcel.TotalWeight,
                            TotalCost = x.Parcel.TotalCost,
                            PaymentType = x.Parcel.PaymentType
                        };
            var office = _myOfficeRepository.GetById(myOfficeId);


            var data = query.ToList();

            var pdfData = new MemoryStream();
            var document = new Document(PageSize.A4, 35, 35, 25, 50);
            var pdfWriter = PdfWriter.GetInstance(document, pdfData);
            pdfWriter.ViewerPreferences = PdfWriter.PageLayoutOneColumn;

            // Our custom Header and Footer is done using Event Handler
            var pageEventHandler = new TwoColumnHeaderFooter();
            pdfWriter.PageEvent = pageEventHandler;

            // Define the page header
            //pageEventHandler.Title = title;
            //pageEventHandler.HeaderFont = FontFactory.GetFont(BaseFont.COURIER_BOLD, 10, Font.BOLD);
            //pageEventHandler.HeaderLeft = "Group";
            //pageEventHandler.HeaderRight = "1";
            var filePath = System.IO.Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Content\\Fonts", "times.ttf");
            BaseFont baseFont = BaseFont.CreateFont("C:\\Windows\\Fonts\\times.ttf", BaseFont.IDENTITY_H, true);
            var fontBold = new Font(baseFont, 10, Font.BOLD, BaseColor.BLACK);
            Font defaultFont = new Font(baseFont, 10, Font.NORMAL, BaseColor.BLACK);

            document.Open();

            //Add header
            var tableColumnHearder = new PdfPTable(2) { WidthPercentage = 100 };
            var colWidthPercentagesHearder = new Single[] { 50, 50 };
            tableColumnHearder.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            tableColumnHearder.SetWidths(colWidthPercentagesHearder);

            string imagepath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Content\\images", "Logo TrungThanh Express.jpg");
            Image img = Image.GetInstance(imagepath);
            img.ScaleToFit(200f, 100f);
            img.Alignment = Image.ALIGN_LEFT;
            img.IndentationLeft = 0f;
            img.SpacingAfter = 9f;
            img.BorderWidthTop = 5f;
            img.BorderColorTop = BaseColor.WHITE;
            tableColumnHearder.AddCell(new PdfPCell(img) { BorderWidth = 0, Padding = 3, HorizontalAlignment = Element.ALIGN_LEFT });

            var myCompany = new Paragraph(office.OfficeName + Environment.NewLine + "Đ/C: " + office.Address + Environment.NewLine + "SĐT: " + office.PhoneNumber + (string.IsNullOrEmpty(office.Fax) ? string.Empty : " FAX: " + office.Fax), defaultFont);
            myCompany.Alignment = Element.ALIGN_RIGHT;
            tableColumnHearder.AddCell(new PdfPCell(myCompany) { BorderWidth = 0, Padding = 3, HorizontalAlignment = Element.ALIGN_RIGHT });
            document.Add(tableColumnHearder);

            //End header

            document.Add(new Paragraph("\r\n"));
            var myTitle = new Paragraph("DANH SÁCH BƯU PHẨM", new Font(baseFont, 22, Font.BOLD, BaseColor.BLACK));
            myTitle.Alignment = Element.ALIGN_CENTER;
            document.Add(myTitle);
            document.Add(new Paragraph("\r\n"));

            //var deliveryFrom = new Chunk("NƠI ĐI: " + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), defaultFont);
            //document.Add(deliveryFrom);
            //document.Add(new Paragraph("\r\n"));

            string deliveryToString;
            var group = _parcelPackagingGroupRepository.GetById(packagingGroupId);
            if (group != null && group.RegionId.HasValue)
            {
                deliveryToString = group.Region.RegionName;
            }
            else
            {
                deliveryToString = "Ngoại Tuyến";
            }
            
            var deliveryTo = new Chunk("NƠI ĐẾN: " + deliveryToString, defaultFont);
            document.Add(deliveryTo);
            document.Add(new Paragraph(""));
            //Report date
            var dateReport = new Chunk("NGÀY: " + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), defaultFont);
            document.Add(dateReport);
            document.Add(new Paragraph("\r\n"));

            //Add columns
            var tableColumn = new PdfPTable(8) { WidthPercentage = 100 };
            var colWidthPercentages = new Single[] { 5, 13, 13, 25, 15, 10, 9, 10 };
            tableColumn.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
            tableColumn.SetWidths(colWidthPercentages);
            tableColumn.AddCell(new PdfPCell(new Phrase("STT", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("S.VẬN ĐƠN", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("KHÁCH GỬI", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("ĐỊA CHỈ", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("NƠI ĐẾN", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("T.LƯỢNG", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("THU HỘ", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            tableColumn.AddCell(new PdfPCell(new Phrase("GHI CHÚ", fontBold)) { Padding = 3, HorizontalAlignment = Element.ALIGN_CENTER });
            document.Add(tableColumn);

            //Add rows
            var no = 1;
            foreach (var item in data)
            {
                var tableRow = new PdfPTable(8) { WidthPercentage = 100 };
                tableRow.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                tableRow.SetWidths(colWidthPercentages);
                tableRow.AddCell(new PdfPCell(new Phrase(no.ToString(), defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                tableRow.AddCell(new PdfPCell(new Phrase(item.TrackingNumbers.ToUpper(), defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                tableRow.AddCell(new PdfPCell(new Phrase(item.CustomerName, defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                tableRow.AddCell(new PdfPCell(new Phrase(item.AddressTo, defaultFont)) { HorizontalAlignment = Element.ALIGN_LEFT });
                tableRow.AddCell(new PdfPCell(new Phrase(item.DeliverToName, defaultFont)) { HorizontalAlignment = Element.ALIGN_CENTER });
                tableRow.AddCell(new PdfPCell(new Phrase(item.Weight + "g", defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                if (item.PaymentType == (int)PaymentTypes.EnumPaymentTypes.Collection)
                {
                    tableRow.AddCell(new PdfPCell(new Phrase(String.Format("{0:0,0}", item.TotalCost), defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                }
                else
                {
                    tableRow.AddCell(new PdfPCell(new Phrase(string.Empty, defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                }
                tableRow.AddCell(new PdfPCell(new Phrase(item.Note, defaultFont)) { HorizontalAlignment = Element.ALIGN_RIGHT });
                document.Add(tableRow);
                no++;
            }

            document.Close();

            return pdfData;
        }
    }
}
